﻿using ChoJu.ModelManager.Config;
using ChongJu.ModelManager.DeviceInfo;
using ChongJu.ModelManager.Rating;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Public.Logger;
using Public.Tools;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace ChongJu.CloudService
{
    public class CloudService
    {
        private string _apiUrl;
        private string _modApiUrl;
        private string _imgApiUrl;
        private HttpMethod _http;

        private List<string> _logs;

        private string _modToken;

        public CloudService()
        {
            _apiUrl = Tool.GetConfig("api");
            _modApiUrl = Tool.GetConfig("modelApi");
            _imgApiUrl = Tool.GetConfig("imgApi");
            _http = new HttpMethod();

            _logs = new List<string>();
        }


        public DeviceSiteModel SearchSiteInfo(string deviceID, out bool isRegist)
        {
            isRegist = false;
            try
            {
                var url = $"{_apiUrl}/site/searchsiteinfo?deviceid={deviceID}";
                var json = _http.WebGet(url, null);
                var res = Tool.JsonToObject<ResponseMode<DeviceSiteModel>>(json);
                if (res.Code == ErrorCodeEnum.NoUser_Mer_ID)
                {
                    isRegist = true;
                    return null;
                }
                if (res.Code != ErrorCodeEnum.Success)
                    return null;

                return res.Data;
            }
            catch (Exception ex)
            {
                Logger.Error("查询站点信息异常", ex);
                UploadLog("查询站点信息异常:" + ex.Message, deviceID);
                return null;
            }
        }

        public bool UploadCurrentVersion(string version, string modVersion, string devID)
        {
            try
            {
                var url = $"{_apiUrl}/device/uploadcurrentversion?version={version}&modVersion={modVersion}&deviceid={devID}";
                var json = _http.WebGet(url, null);
                var res = Tool.JsonToObject<ResponseMode<DeviceSiteModel>>(json);
                return res.Code == ErrorCodeEnum.Success;
            }
            catch (Exception ex)
            {
                Logger.Error("上报版本信息异常", ex);
                return false;
            }
        }

        public bool RegistDevice(string deviceID)
        {
            try
            { 
                //type= 1分级  2定级  3主控 4便携式
                var url = $"{_apiUrl}/device/create?deviceid={deviceID}&type=4&version={Tool.GetAppVersion()}";
                var json = _http.WebGet(url, null);
                var res = Tool.JsonToObject<ResponseMode<DeviceSiteModel>>(json);
                return res.Code == ErrorCodeEnum.Success;
            }
            catch (Exception ex)
            {
                Logger.Error("注册设备异常", ex);
                return false;
            }
        }

        public string DownloadSystemVersion(string versoin)
        {
            try
            {
                var url = $"{_apiUrl}/version/downloadversionapp?version={versoin}&type=4";
                var data = _http.ByteWebGet(url, null);
                var dir = Path.Combine(AppContext.BaseDirectory, "Version");
                if (Directory.Exists(dir) == false)
                    Directory.CreateDirectory(dir);

                var fileName = Path.Combine(dir, $"{versoin}.zip");
                Tool.BytesFile(data, fileName);
                return fileName;
            }
            catch (Exception ex)
            {
                Logger.Error("下载系统版本异常", ex);
                return null;
            }
        }

        public bool SendWeightInfo(WeightModel data)
        {
            try
            {
                var url = $"{_apiUrl}/account/weightinfo";
                var tmp = _http.SendPost(null, url, Tool.ConvertToByteArray(data));
                var str = Encoding.UTF8.GetString(tmp);
                var res = Tool.JsonToObject<ResponseMode>(str);

                return res.Code == ErrorCodeEnum.Success;
            }
            catch (Exception ex)
            {
                Logger.Error("发送重量信息异常", ex);
                return false;
            }

        }

        public bool Login()
        {
            try
            {
                if (string.IsNullOrEmpty(_modToken) == false)
                    return true;

                var url = $"{_modApiUrl}/sys/user/login";
                var bytes = _http.SendPost("", url, null);
                var temp = Encoding.UTF8.GetString(bytes);
                JObject json = (JObject)JsonConvert.DeserializeObject(temp);
                if (json == null)
                    return false;
                _modToken = json["token"].ToString();
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error("登录图片服务异常", ex);
                return false;
            }
        }

        public string GetBatchNo(string location, string station, string variety, string part)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(_modToken) == true)
                {
                    var login = Login();
                    if (login == false)
                        return null;
                }

                var url = $"{_modApiUrl}/tbco/data/save";
                dynamic request = new { location = location, station = station, variety = variety, part = part, remark = "each" };
                var res = _http.SendPostJson(_modToken, url, Tool.ObjectToJson(request));
                JObject json = (JObject)JsonConvert.DeserializeObject(res);
                if (json == null || json["code"].ToString() != "200")
                    return "获取批次号失败";

                var no = json["data"].ToString();
                return no;
            }
            catch (Exception ex)
            {
                Logger.Error("获取图片上传批次号异常", ex);
                return string.Empty;
            }
        }

        public List<ModsModel> GetTemplateList(string siteName, string type)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(_modToken) == true)
                {
                    var login = Login();
                    if (login == false)
                        return null;
                }

                siteName = "界头烟站";
                var url = $"{_modApiUrl}/mod/info/list1?station={siteName}&remark={type}";
                var res = _http.WebGet(url, _modToken);
                JObject json = (JObject)JsonConvert.DeserializeObject(res);
                if (json == null || json["code"].ToString() != "200")
                    return null;

                var dataStr = json["data"].ToString();
                var data = Tool.JsonToObject<List<ModsModel>>(dataStr);
                return data;
            }
            catch (Exception ex)
            {
                Logger.Error("获取模型列表异常", ex);
                return null;
            }
        }

        public string DownloadMod(string modNum)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(_modToken) == true)
                {
                    var login = Login();
                    if (login == false)
                        return null;
                }

                var url = $"{_modApiUrl}/mod/data/download?modNum={modNum}";
                var res = _http.WebGet(url, _modToken);
                JObject json = (JObject)JsonConvert.DeserializeObject(res);
                if (json == null || json["code"].ToString() != "200")
                    return null;

                var dataStr = json["data"].ToString();
                return dataStr;
            }
            catch (Exception ex)
            {
                Logger.Error("获取模型列表异常", ex);
                return null;
            }
        }

        public string UploadImage(byte[] img, string site, string batchNo, string levCode, double weight, float height, string type, string imageName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(_modToken) == true)
                {
                    var login = Login();
                    if (login == false)
                        return "登录失败";
                }

                var url = $"{_imgApiUrl}/tbco/data/upfile?station=eeee&type={type}&tbcoNum={batchNo}&height={height}&labelName={levCode}&imageName={imageName}&weight={weight}&remark={type}";
                var res = _http.SendPost(_modToken, url, img);
                var tmp = Encoding.UTF8.GetString(res);
                JObject json = (JObject)JsonConvert.DeserializeObject(tmp);
                if (json == null)
                {
                    Logger.Debug(tmp);
                    return "上传图片失败";
                }
                else if (json["code"].ToString() != "200")
                {
                    Logger.Debug(tmp);
                    return json["msg"]?.ToString();
                }

                return null;
            }
            catch (Exception ex)
            {
                Logger.Error("上传图片异常", ex);
                return ex.Message;
            }
        }

        public string EndImageCollect(string batcbNo, string type)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(_modToken) == true)
                {
                    var login = Login();
                    if (login == false)
                        return null;
                }

                var url = $"{_modApiUrl}/tbco/data/update?tbcoNum={batcbNo}&remark={type}";
                var res = _http.WebGet(url, _modToken);
                JObject json = (JObject)JsonConvert.DeserializeObject(res);
                if (json == null)
                    return "结束采集失败";
                else if (json["code"].ToString() != "200")
                    return json["msg"]?.ToString();

                return null;
            }
            catch (Exception ex)
            {
                Logger.Error("结束采集异常", ex);
                return null;
            }
        }

        public string GetDllLastVersion()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(_modToken) == true)
                {
                    var login = Login();
                    if (login == false)
                        return null;
                }

                var url = $"{_modApiUrl}/auto/libDll/getVersion?remark=each";
                var res = _http.WebGet(url, _modToken);
                JObject json = (JObject)JsonConvert.DeserializeObject(res);
                if (json == null)
                    return "获取模型dll版本失败";


                var dataStr = json["data"].ToString();
                return dataStr;
            }
            catch (Exception ex)
            {
                Logger.Error("获取模型dll版本异常", ex);
                return null;
            }
        }

        public bool DownloadDll(string name, string filePath)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(_modToken) == true)
                {
                    var login = Login();
                    if (login == false)
                        return false;
                }

                var url = $"{_modApiUrl}/auto/libDll/getZip?version={name}";
                var data = _http.ByteWebGet(url, _modToken);
                Tool.BytesFile(data, filePath);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error("下载dll文件异常", ex);
                return false;
            }
        }

        public string GetModnoByUnitID(string unitID)
        {
            try
            {
                var url = $"{_apiUrl}/unit/searchmodnobyunitid?unitid={unitID}";
                var res = _http.WebGet(url, _modToken);
                var result = Tool.JsonToObject<ResponseMode>(res);
                return result.Data?.ToString();
            }
            catch (Exception ex)
            {
                Logger.Error("获取模型dll版本异常", ex);
                return null;
            }
        }

        public bool UploadDataInfo(string data)
        {
            try
            {
                var url = $"{_apiUrl}/device/statssingleinfo";
                var tmp = _http.SendPost(null, url, Tool.ConvertToByteArray(data));
                var str = Encoding.UTF8.GetString(tmp);
                var result = Tool.JsonToObject<ResponseMode>(str);
                if (result.Code != ErrorCodeEnum.Success)
                    Logger.Error(result?.Message);

                return result.Code == ErrorCodeEnum.Success;
            }
            catch (Exception ex)
            {
                Logger.Error("上传分拣等级数据异常", ex);
                return false;
            }
        }

        public bool UploadDataInfoOne(string deviceID, string levCode, int count)
        {
            try
            {
                var url = $"{_apiUrl}/device/statssingleinfo?devid={deviceID}&levcode={levCode}&count={count}";
                var tmp = _http.WebGet(url, null);
                var result = Tool.JsonToObject<ResponseMode>(tmp);
                if (result.Code != ErrorCodeEnum.Success)
                    Logger.Error(result?.Message);

                return result.Code == ErrorCodeEnum.Success;
            }
            catch (Exception ex)
            {
                Logger.Error("上传分拣等级数据异常", ex);
                return false;
            }
        }

        public byte[] DownloadModZip(int autoid)
        {
            if (string.IsNullOrWhiteSpace(_modToken) == true)
            {
                var login = Login();
                if (login == false)
                    return null;
            }

            var url = $"{_modApiUrl}/auto/data/downloadzip?autoId={autoid}";
            var data = _http.ByteWebGet(url, _modToken);
            return data;
        }

        /// <summary>
        /// 向云端发送异常日志
        /// </summary>
        /// <param name="message"></param>
        public void UploadLog(string message, string deviceID)
        {
            if (_logs.Exists(e => e == message) == true)
                return;
            else
                _logs.Add(message);

            Task.Run(() =>
            {
                try
                {
                    var url = $"{_apiUrl}/device/uploadlog?deviceid={deviceID}";
                    var bytes = Encoding.UTF8.GetBytes(message);
                    var tmp = _http.SendPost(null, url, bytes);
                }
                catch(Exception ex)
                {
                    Logger.Error("发送日志信息异常", ex);
                }
            });
        }

        public void SendLocation(string country, string region, string city, string ip, double lat, double lon, string devID)
        {
            try
            {
                var url = $"{_apiUrl}/device/uploadlocation?" +
                $"country={country}&" +
                $"region={region}&" +
                $"city={city}&" +
                $"ip={ip}&" +
                $"lat={lat}&" +
                $"lon={lon}&" +
                $"devID={devID}";
                var tmp = _http.WebGet(url, null);
            }
            catch (Exception ex)
            {
                Logger.Error("上传地理位置异常", ex);
            }
        }

        public bool? ConfigFileExist(string deviceID)
        {
            var url = $"{_apiUrl}/device/configfileexist?deviceid={deviceID}";
            var tmp = _http.WebGet(url, null);
            var result = Tool.JsonToObject<ResponseMode>(tmp);
            if (result.Code == ErrorCodeEnum.Success)
            {
                var exist = result.Data as bool?;
                return exist == true;
            }
            else
                Logger.Error(result?.Message);

            return null;
        }

        public void UploadConfigFiles(string deviceID)
        {
            Task.Run(() =>
            {
                var dirRoot = Path.Combine(AppContext.BaseDirectory, "Config");
                if (Directory.Exists(dirRoot) == false)
                {
                    Logger.Debug("没有配置文件");
                    return;
                }

                var files = Directory.GetFiles(dirRoot);
                if (files.Length == 0)
                {
                    Logger.Debug("没有配置文件项目");
                    return;
                }

                List<ConfigSaveModel> lst = new List<ConfigSaveModel>();
                foreach (var file in files)
                    lst.Add(new ConfigSaveModel()
                    {
                        DeviceID = deviceID,
                        Name = new FileInfo(file).Name,
                        Content = File.ReadAllText(file)
                    });

                var url = $"{Tool.GetConfig("api")}/config/upload";
                string json = JsonConvert.SerializeObject(lst);
                var data = Encoding.UTF8.GetBytes(json);

                var response = HttpReqest.PostBytes(url, data);
                JObject jsonObj = JObject.Parse(response);

                string code = (string)jsonObj["code"];
                if (code != "0")
                    Logger.Debug("上传配置文件失败");
                else
                    Logger.Debug("上传配置文件成功");
            });
        }
    }
}
